package Parser;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.DOMBuilder;
import org.xml.sax.SAXException;

public class ParserJDOM {

	private Element root;
	private Element current;
	private boolean findOk = false;

	public void parse(String fileName) {
		Document jdomDoc;
		try {
			// we can create JDOM Document from DOM, SAX and STAX Parser Builder
			// classes
			jdomDoc = useDOMParser(fileName);
			root = jdomDoc.getRootElement();
			System.out.println(root.getName());

			// lets print Employees list information

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static Document useDOMParser(String fileName)
			throws ParserConfigurationException, SAXException, IOException {
		// creating DOM Document
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder;
		dBuilder = dbFactory.newDocumentBuilder();
		DOMBuilder domBuilder = new DOMBuilder();
		return domBuilder.build(dBuilder.parse(new File(fileName)));

	}

	public Element searchElement(String element) {

		if (current.getName().equals(element)) {
			return current;
		} else {
			for (Element child : current.getChildren()) {
				current = child;
				if (searchElement(element) != null) {
					return searchElement(element);
				}
			}
		}

		return null;

	}

	public void resetRoot() {

		current = root;

	}

	public void setCurrent(Element elem) {
		current = elem;
	}

	public Element getRoot() {
		return root;
	}
}
